<?php
Loader::loadClass('AntiSpam', "modules/InnoForum/pnincludes");
class PNTopics extends PNObjectEx {
  function PNTopics($init=null, $where='')
  {
    $this->PNObject();

    $this->_objType       = 'innoforum_topics';
    $this->_objField      = 'id';
    $this->_objPath       = 'form';

    //permission for post new | edit topic
    $func = FormUtil::getPassedValue ('func', false);
    $ctrl = FormUtil::getPassedValue ('ctrl', false);
    $this->_objPermission = array('component' => "InnoForum:$func:$ctrl",
                                  'instance'  => '.*',
                                  'level'     => USER_EDIT_LEVEL);
    $this->_init($init, $where);
  }


  function validate(){
    $form = FormUtil::getPassedValue ('form', false);
    $is_validate = true;
    if (empty($form['title'])){
      $error = "ขออภัย ประกาศไม่มีหัวข้อกรุณาใส่หัวข้อ";
      SessionUtil::setVar('YLERROR', $error, '/', true, true);
      $is_validate = false;
    }
    $wc = AntiSpam::str_match_count('href',$form['detail']);
    if ($wc  >= 2){
      $error = "ขออภัย ห้ามใส่ลิงค์มากกว่า 1 ลิงค์";
      SessionUtil::setVar('YLERROR', $error, '/', true, true);
      $is_validate = false;
    }

    if (iconv_strlen($form['detail'],"UTF-8") <= 10 ){
      $error = "ขออภัย รายละเอียดของประกาศสั้นเกินไป";
      SessionUtil::setVar('YLERROR', $error, '/', true, true);
      $is_validate = false;
    }


    //Valiadate image type & extendsion
    $images = $_FILES['images'];
    if(isset($images)){
      foreach ($images["error"] as $key => $error){
        $tmp_name = $images["tmp_name"][$key];
        $fliename = $images["name"][$key];
        $filetype = $images["type"][$key];
        $filesize = $images["size"][$key];

        $filename = stripslashes($fliename);
        $i = strrpos($filename,".");
        //if (!$i) { return ""; }
        $l = strlen($filename) - $i;
        $ext = substr($filename,$i+1,$l);
        $extension = strtolower($ext);
        
        $validate = 0;
        //image/jpeg
        if($extension == "jpeg" || $extension == "jpg" || $extension == "png" || ($filesize == 0 && $filename == "")){
          if (($filetype == "image/jpg")|| 
              ($filetype == "image/pjpeg")|| 
              ($filetype == "image/jpeg")|| 
              ($filetype == "image/png")
            ) {
              if ($error > 0) {
                $error = "ขออภัย  truck2hand  อนุญาติให้อัพโหลดไฟล์ .jpg, .jpeg และ .png";
                SessionUtil::setVar('YLERROR', $error, '/', true, true);
                $is_validate = false;
              }else{
                $is_validate = true;
              }
          }else if($filetype == ""){
            $is_validate = true;
         }else{
              $error = "ขออภัย  truck2hand  อนุญาติให้อัพโหลดไฟล์ .jpg, .jpeg และ .png";
              SessionUtil::setVar('YLERROR', $error, '/', true, true);
              $is_validate = false;
          }
        }else{
          $ctrl =  FormUtil::getPassedValue ('ctrl', null);              
          $error = "ขออภัย truck2hand อนุญาติให้อัพรูปประเภท jpg, jpeg และ png เท่านั้น";
          SessionUtil::setVar('YLERROR', $error, '/', true, true);
          $is_validate = false;
          return $is_validate;
        }
      }
    }

    return $is_validate;
  }

/*
  function validate(){
    $form = FormUtil::getPassedValue ('form', false);
    $is_validate = 0;
    $wc = AntiSpam::str_match_count('href',$form['detail']);
    if (empty($form['title'])){
      //$error = "ขออภัย ประกาศไม่มีหัวข้อกรุณาใส่หัวข้อ";
      //$error = "1";
      //SessionUtil::setVar('YLERROR', $error, '/', true, true);
      $is_validate = 1;
    } else if ($wc  >= 2){
      //$error = "2";
      //$error = "<center>ขออภัย ห้ามใส่ลิงค์มากกว่า 1 ลิงค์</center>";
      //SessionUtil::setVar('YLERROR', $error, '/', true, true);
      $is_validate = 2;
    }else if (iconv_strlen($form['detail'],"UTF-8") <= 10 ){
      //$error = "3";
      //$error = "ขออภัย รายละเอียดของประกาศสั้นเกินไป";
      //SessionUtil::setVar('YLERROR', $error, '/', true, true);
      $is_validate = 3;
    }
    return $is_validate;
  }
*/

  function updatePreProcess(){
    //check to delete icon or model or video
    $form = FormUtil::getPassedValue ('form', false );
    $id = $this->objData['id'];
    $this->_objData['ipaddress'] = InnoUtil::getIpAddress();
    $this->checkColor();
  }

  function insertPreProcess(){
    //get ip address
    $this->_objData['ipaddress'] = InnoUtil::getIpAddress();
    $this->checkColor();
  }

  function insertPostProcess(){
    //Insert image
    Loader::loadClass('DataUtilEx', "modules/InnoForum/pnincludes");
    $id = DBUtil::getInsertID ($this->_objType, $this->_objField);
    if ($id){
      //set ref_id
      //get category prefix
      $cate = DBUtil::selectFieldByID('innoforum_category','prefix',$this->_objData['category_id']);
      $subcate = DataUtilEx::fillString($this->_objData['subcategory_id'],2,'0');
      $ref_id = DataUtilEx::fillString($id,5,'0', $cate . $subcate);
      $cr_date = $this->_objData['cr_date'];
      //$object = array('id'=>$id,'ref_id'=>$ref_id,'temp_cr_date'=>date("Y-m-d H:i:s"));
      $object = array('id'=>$id,'ref_id'=>$ref_id,'temp_cr_date'=>$cr_date);
      DBUtil::updateObject($object,$this->_objType);
      $this->uploadFiles($id);
      $this->checkHasImage($id);
    }
  }

  function updatePostProcess(){
    //set thumb to image status
    $form = FormUtil::getPassedValue ('form', false );
    $id = $this->_objData['id'];

    $thumb_id = $form['image_thumb'];

    //set lastupdate
    if($id){
      $lastupdate = date("Y-m-d");
      $object = array('lastupdate'=>$lastupdate);
      $where  = " tpc_id = ".$id;
      DBUtil::updateObject($object,'innoforum_topics',$where);
    }

    //set image thumb
    if ($thumb_id && $id){
      //clear status
      $object = array('status' => 0);
      $where = "WHERE rsi_path = 'topics' AND rsi_referer_id = '$id'";
      DBUtil::updateObject($object,'innoforum_resource_image',$where);
      //set thumb
      $object = array('id' => $thumb_id , 'status' => 1);
      DBUtil::updateObject($object,'innoforum_resource_image');

      //Set first image to topics table
      $columnArray = array('filename','thumbname');
      $firstimage = DBUtil::selectObject('innoforum_resource_image' ,
                                              "WHERE rsi_referer_id = '$id' AND rsi_path = 'topics' AND rsi_status = 1",
                                              $columnArray
                                            );

      $object = array('firstimage'=>$firstimage[filename] , 'firsthumbimage'=>$firstimage[thumbname]);
      $where  = " tpc_id = ".$id;
      if ($id && $firstimage[filename]){
        DBUtil::updateObject($object,'innoforum_topics',$where);
      }
    }

    //delete image
    foreach($form['image_delete'] as $delete_id){
      //Delete file from directory
      $columnArray = array('filename','thumbname');
      $objectImageName = DBUtil::selectObject('innoforum_resource_image',
                                              "WHERE rsi_path = 'topics' AND rsi_id = '$delete_id)'",
                                              $columnArray);
      unlink('pnTemp/innoforum_upload/'.$objectImageName['filename']);
      unlink('pnTemp/innoforum_upload/'.$objectImageName['thumbname']);

      DBUtil::deleteObjectByID('innoforum_resource_image',$delete_id);
    }
    $this->uploadFiles($id);
    $this->checkHasImage($id);
  }

  function uploadFiles($id){
    $count = DBUtil::selectObjectCount('innoforum_resource_image' , "WHERE rsi_referer_id = '$id' AND rsi_path = 'topics'");

    if ($id && in_array(0,$_FILES['images']['error'])){
      $images = $_FILES['images'];
      
      //Original value
      //$imagespath = "resource/innoforum_upload/large/".$id."/";
      //$thumbspath = "resource/innoforum_upload/medium/".$id."/";


      $fakeId = ($id-41538);
      if($fakeId % 10000 == 0){
        $newNumberOfDirectory = ($fakeId/10000);
        $imagespath = "resource/innoforum_upload/large".$newNumberOfDirectory."/".$id."/";
        $thumbspath = "resource/innoforum_upload/medium".$newNumberOfDirectory."/".$id."/";
      }else if($id < 41538){
        $imagespath = "resource/innoforum_upload/large/".$id."/";
        $thumbspath = "resource/innoforum_upload/medium/".$id."/";
      }else{
        $imagespath = "resource/innoforum_upload/large".floor($fakeId/10000)."/".$id."/";
        $thumbspath = "resource/innoforum_upload/medium".floor($fakeId/10000)."/".$id."/";
      }


      //Make topic image directory by id
      if (!is_dir($imagespath)) {
        mkdir($imagespath, 0755);
      }
      //Make topic thumb directory by id
      if (!is_dir($thumbspath)) {
        mkdir($thumbspath, 0755);
      }

      foreach ($images["error"] as $key => $error){
        if ($error == 0){
            //Gennerate next id
            $image_id = DBUtil::selectFieldMax( 'innoforum_resource_image', 'id', 'MAX', '');
            if($image_id == null){
              $next_id = 1;
            }else{
              $next_id = $image_id+1;
            }

            $tmp_name = $images["tmp_name"][$key];
            $fliename = $images["name"][$key];
            $filetype = $images["type"][$key];
            $filesize = $images["size"][$key];

////////////////////////// get the extension of the file in a lower case format/////////////////////////////////////////////
            $filename = stripslashes($fliename);
            $i = strrpos($filename,".");
            if (!$i) { return ""; }
            $l = strlen($filename) - $i;
            $ext = substr($filename,$i+1,$l);
            $extension = strtolower($ext);

////////////////////////////generate new file&path/////////////////////////////////////////////////////////////////////
            $rootname       = $next_id.time().".".$extension;
            $filename_temp  = "images_".$id.$rootname;
            $thumbname_temp = "thumbs_".$id.$rootname;
            $imgpath        = $imagespath.$filename_temp;
            $tmbpath        = $imagespath.$filename_temp;

            if($key==0){
              $firstimage_temp = $filename_temp;
            }

//////////////////////////start upload/////////////////////////////////////////////

        $source = $tmp_name;
        $target = $imgpath;
        move_uploaded_file($source, $target);

        //images
        $imagepath = $fliename;
        $save = $imgpath;; //This is the new file you saving
        $file = $imgpath; //This is the original file
        list($width, $height) = getimagesize($file) ; 

//////////////////resize image orginal////////////////////
        $modwidth = 600; 
        $diff = $width / $modwidth;
        if (($width > 600) || ($height > 200)) 
        {
          $modheight = $height / $diff; 
          $tn = imagecreatetruecolor($modwidth, $modheight); 
          if($filetype == "image/pjpeg" || $filetype == "image/jpeg"){
            $image = imagecreatefromjpeg($file) ; 
          }elseif($filetype == "image/x-png" || $filetype == "image/png"){
            $image = imagecreatefrompng($file) ;
          }elseif($filetype == "image/gif"){
            $image = imagecreatefromgif($file) ;
          }
            imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ; 
        }

        if($filetype == "image/pjpeg" || $filetype == "image/jpeg"){
          imagejpeg($tn, $save, 100) ; 
        }elseif($filetype == "image/x-png" || $filetype == "image/png"){
          imagepng($tn, $save) ; 
        }elseif($filetype == "image/gif"){
          copy($file, $save) ; 
        }

//////////////////resize image thumb////////////////////

        $save = $tmbpath; //This is the new file you saving
        $file = $imgpath; //This is the original file

        list($width, $height) = getimagesize($file) ; 

        $modwidth = 100; 
        $diff = $width / $modwidth;
        $modheight = $height / $diff; 
        $tn = imagecreatetruecolor($modwidth, $modheight); 
        if($filetype == "image/pjpeg" || $filetype == "image/jpeg"){
          $image = imagecreatefromjpeg($file) ; 
        }elseif($filetype == "image/x-png" || $filetype == "image/png"){
          $image = imagecreatefrompng($file) ;
        }elseif($filetype == "image/gif"){
          $image = imagecreatefromgif($file) ;
        }
        imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ; 

        if($filetype == "image/pjpeg" || $filetype == "image/jpeg"){
          imagejpeg($tn, $save, 100) ; 
        }elseif($filetype == "image/x-png" || $filetype == "image/png"){
          imagepng($tn, $save) ; 
        }elseif($filetype == "image/gif"){
          copy($file, $save) ; 
        }

            //destroys source and destination images.
            //imagedestroy($dst_img);
            //imagedestroy($src_img);

            $objects = array(
                            'id'         => $next_id,
                            'path'       => 'topics',
                            'referer_id' => $id,
                            'filename'   => $filename_temp,
                            'filesize'   => $filesize,
                            'filetype'   => $filetype,
                            'thumbname'  => $filename_temp,
                            'thumbsize'  => $thumbsize,
                            'thumbtype'  => $thumbtype
                           );

          DBUtil::insertObject($objects,'innoforum_resource_image');

        }
      }
      //Set default images
      if ($id && $count==0){
        $object = array('firstimage'=>$firstimage_temp , 'firsthumbimage'=>$firstimage_temp);
        $where  = " tpc_id = ".$id;
        DBUtil::updateObject($object,'innoforum_topics',$where);
      }
    }
  }
  function deletePreProcess(){

    $id = $this->_objData['id'];

    //Topics path
    $images_topics_path = "resource/innoforum_upload/large/".$id;
    $thumbs_topics_path = "resource/innoforum_upload/medium/".$id;

    if($id){
      $this->deleteDirectory($images_topics_path);
      $this->deleteDirectory($thumbs_topics_path);

      //delete topic
      DBUtil::deleteWhere('innoforum_topics',"WHERE tpc_id = '$id'");

      //delete post
      DBUtil::deleteWhere('innoforum_posts',"WHERE pst_topics_id = '$id'");
      DBUtil::deleteWhere('innoforum_resource_image',"WHERE rsi_referer_id = '$id' AND rsi_path = 'posts'");

      //delete image
      DBUtil::deleteWhere('innoforum_resource_image',"WHERE rsi_referer_id = '$id' AND rsi_path = 'topics'");
    }
  }
  
  function deleteDirectory($dirname) {
    if (is_dir($dirname))
       $dir_handle = opendir($dirname);
    if (!$dir_handle)
       return false;
    while($file = readdir($dir_handle)) {
       if ($file != "." && $file != "..") {
          if (!is_dir($dirname."/".$file))
             unlink($dirname."/".$file);
          else
             $this->deleteDirectory($dirname.'/'.$file);    
       }
    }
    closedir($dir_handle);
    rmdir($dirname);
    return true;
  }

  function selectExtendResult(){
    $id = FormUtil::getPassedValue ('id', false );
    $result = array();
    if ($id){
      $result['images'] = DBUtil::selectObjectArray('innoforum_resource_image' , "WHERE rsi_referer_id = '$id' AND rsi_path = 'topics'" , '', -1, -1,
                                '', null, null, array('id','filename','thumbname'));
    }

    return $result;
  }

  function checkColor(){
    if ($this->_objData['bgcolor'] == '#000000'){
      $this->_objData['bgcolor'] = '';
    }
  }

  function checkHasImage($id){
    $count = DBUtil::selectObjectCount('innoforum_resource_image' , "WHERE rsi_referer_id = '$id' AND rsi_path = 'topics'");
    if ($count && $id){
      $object = array('id'=>$id , 'has_image'=>$count);
      DBUtil::updateObject($object,$this->_objType);
    }else{
      $object = array('id'=>$id , 'has_image'=>0);
      DBUtil::updateObject($object,$this->_objType);
    }
  }

}